﻿using GameData.Common;
using GameData.Domains;
using GameData.Domains.Character;
using GameData.Domains.CombatSkill;
using GameData.Domains.Map;
using GameData.Domains.TaiwuEvent.EventHelper;
using GameData.Utilities;
using HarmonyLib;
using System;
using TaiwuModdingLib.Core.Plugin;


namespace CombatSkillMasterBackend
{
    [PluginConfig("CombatSkillMaster", "HMS Unicorn", "0.2")]
    public class CombatSkillMasterBackendPlugin : TaiwuRemakePlugin
    {
        Harmony harmony;

        bool additionCombatSkill;
        bool fullPractice;
        bool fullPages;
        bool zeroBreakCostExp;

        public override void Dispose()
        {
            AdaptableLog.Info("CombatSkillMasterBackendPlugin.Dispose");
            if (harmony != null)
            {
                harmony.UnpatchSelf();
            }
        }

        public override void Initialize()
        {
            AdaptableLog.Info("CombatSkillMasterBackendPlugin.Initialize");
            harmony = Harmony.CreateAndPatchAll(typeof(CombatSkillMasterBackendPlugin));
            
            DomainManager.Mod.GetSetting(base.ModIdStr, "AdditionCombatSkill", ref additionCombatSkill);
            DomainManager.Mod.GetSetting(base.ModIdStr, "FullPractice", ref fullPractice);
            DomainManager.Mod.GetSetting(base.ModIdStr, "FullPages", ref fullPages);
            DomainManager.Mod.GetSetting(base.ModIdStr, "ZeroBreakCostExp", ref zeroBreakCostExp);
        }

        public void LearnAllCombatSkills()
        {
            AdaptableLog.Info("CombatSkillMasterBackendPlugin.LearnAllCombatSkills");
            AdaptableLog.Info(String.Format("TaiwuCharId: {0}", DomainManager.Taiwu.GetTaiwuCharId()));
            Character taiwu = DomainManager.Taiwu.GetTaiwu();
            DataContext context = DataContextManager.GetCurrentThreadDataContext();

            //// 1. 学习功法并读完所有15书页
            //DomainManager.Taiwu.TaiwuLearnCombatSkill(context, Config.CombatSkill.DefKey.WuDangChunYangQuan, 0xFFFF);
            //// 不能用这个 taiwu.LearnNewCombatSkill(context, Config.CombatSkill.DefKey.WuDangChunYangQuan, 0, 0); // 0xFF >> 1);

            //// 2. 修习到100熟练度
            //CombatSkill skill = DomainManager.CombatSkill.GetElement_CombatSkills(
            //    new CombatSkillKey(taiwu.GetId(), Config.CombatSkill.DefKey.WuDangChunYangQuan));
            //skill.SetPracticeLevel(100, context);

            Config.CombatSkill.Instance.Iterate(skillItem =>
            {

                if (!additionCombatSkill)
                {
                    if (726 <= skillItem.TemplateId && skillItem.TemplateId <= 879)
                    {
                        AdaptableLog.Info(String.Format("跳过功法: {0} {1}", skillItem.Name, skillItem.TemplateId));
                        return true;
                    }
                }

                // 学习未学习的功法
                if (DomainManager.Taiwu.TryGetElement_CombatSkills(skillItem.TemplateId, out _))
                {
                    
                }
                else
                {
                    AdaptableLog.Info(String.Format("学习功法: {0} {1}", skillItem.Name, skillItem.TemplateId));
                    DomainManager.Taiwu.TaiwuLearnCombatSkill(context, skillItem.TemplateId);
                }
                var skill = DomainManager.CombatSkill.GetElement_CombatSkills(
                    new CombatSkillKey(taiwu.GetId(), skillItem.TemplateId)
                );

                if (fullPractice)
                {
                    skill.SetPracticeLevel(100, context);
                }

                if (fullPages)
                {
                    skill.SetReadingState(0xFFFF, context);
                }

                // 726 到 748 都是内功，突破后人物被击败时不会有第二条血，而是会出bug，因此取消突破
                if (749 <= skillItem.TemplateId && skillItem.TemplateId <= 879)
                {
                    skill.SetActivationState(994, context);
                    DomainManager.SpecialEffect.Add(context, taiwu.GetId(), skillItem.TemplateId, 3);  // 默认正练效果
                    AdaptableLog.Info(String.Format("功法正练: {0} {1} {2}", skillItem.Name, skillItem.TemplateId, skill.GetSpecialEffectId()));
                }
                return true;
            });
        }

        private unsafe void ForceSetCostExpToZero(Config.SkillBreakPlateItem plateItem)
        {
            fixed (short* ptr = &plateItem.CostExp) *ptr = 0;
        }

        public void SetAllBreakPlateCostExpToZero()
        {
            Config.SkillBreakPlate.Instance.Iterate(plateItem =>
            {
                ForceSetCostExpToZero(plateItem);
                AdaptableLog.Info($"{plateItem.TemplateId} CostExp set to: {plateItem.CostExp}");
                return true;
            });
        }

        public override void OnEnterNewWorld()
        {
            AdaptableLog.Info("CombatSkillMasterBackendPlugin.OnEnterNewWorld");
        }

        public override void OnLoadedArchiveData()
        {
            AdaptableLog.Info("CombatSkillMasterBackendPlugin.OnLoadedArchiveData");
            LearnAllCombatSkills();
            if (zeroBreakCostExp) { SetAllBreakPlateCostExpToZero(); }
        }

        // 为了解决读取开局存档时使用此Mod导致的重复学习功法报错的Bug，方法是禁止太吾本人在事件中学习功法
        [HarmonyPrefix]
        [HarmonyPatch(typeof(EventHelper), "LearnCombatSkill")]
        public static bool EventHelper_LearnCombatSkill_PreFix(int charId, short skillId)
        {
            AdaptableLog.Info("Enter EventHelper_LearnCombatSkill_PreFix");
            if (charId == DomainManager.Taiwu.GetTaiwuCharId() && DomainManager.Taiwu.TryGetElement_CombatSkills(Config.CombatSkill.DefKey.WuDangChunYangQuan, out _)) { return false; }
            return true;
        }
    }
}
